package com.sweet.jpa.factory;

import com.sweet.jpa.repository.BaseRepositoryImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * 通用持久层工厂
 *
 * @author limi
 * @create 2018-03-19-11:56
 */
@Slf4j
public class BaseRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {
    public BaseRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        log.info("创建BaseRepositoryFactory");
        return new BaseRepositoryFactory(em);
    }

    /**
     * 创建一个内部类，该类不用在外部访问
     *
     * @param <T>
     * @param <I>
     */
    private static class BaseRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {
        public BaseRepositoryFactory(EntityManager em) {
            super(em);
        }

        /**
         * 设置具体的实现类是BaseRepositoryImpl
         *
         * @param information
         * @param entityManager
         * @return
         */
        @Override
        protected JpaRepositoryImplementation<?, ?> getTargetRepository(RepositoryInformation information, EntityManager entityManager) {
            log.info("创建BaseRepositoryImpl");
            //return super.getTargetRepository(information, entityManager);
            return new BaseRepositoryImpl<T, I>((Class<T>) information.getDomainType(), entityManager);
        }

        //设置具体的实现类的class
        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return BaseRepositoryImpl.class;
        }
    }
}